import {
  getAdminMessageTable,
  sendMessageRecord
} from '../../api/content'
import {
  ADMIN_MESSAGE_LIST,
  ADMIN_MESSAGE_DATA_COUNT,
  ADMIN_MESSAGE_CURRENT_ROW,
  ADMIN_MESSAGE_HISTORY_DATA,
  ADMIN_MESSAGE_PAGE_SIZE
} from '../motations-type'

export default {
  state: {
    adminMessageList: [],
    adminMessageDataCount: null,
    adminMessagePageSize: 20,
    adminMessageHistoryData: [],
    row: {
      title: '',
      state: '',
      ctime: '',
      operater: '',
      content: ''
    }
  },
  getters: {
    adminMessageList: state => state.adminMessageList
  },
  mutations: {
    [ADMIN_MESSAGE_LIST] (state, data) {
      state.adminMessageList = data
    },
    [ADMIN_MESSAGE_CURRENT_ROW] (state, data) {
      state.row = data
    },
    [ADMIN_MESSAGE_DATA_COUNT] (state, data) {
      state.adminMessageDataCount = data
    },
    [ADMIN_MESSAGE_HISTORY_DATA] (state, data) {
      state.adminMessageHistoryData = data
    },
    [ADMIN_MESSAGE_PAGE_SIZE] (state, data) {
      state.adminMessagePageSize = data
    }
  },
  actions: {
    async getAdminMessageList ({ commit, rootState }, playload) {
      let data = {}
      let newData = []
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      const resp = await getAdminMessageTable(data)
      // console.log(resp)
      resp.data.data.rows.map((item) => {
        newData = [...newData, {
          title: item.title,
          state: item.state,
          ctime: item.ctime,
          operater: item.ctime,
          content: item.content
        }]
      })
      commit(ADMIN_MESSAGE_LIST, newData)
      commit(ADMIN_MESSAGE_DATA_COUNT, resp.data.data.total)
      if (newData.length < rootState.adminMessage.adminMessagePageSize) {
        commit(ADMIN_MESSAGE_HISTORY_DATA, newData)
      } else {
        commit(ADMIN_MESSAGE_HISTORY_DATA, newData.slice(0, rootState.adminMessage.adminMessagePageSize))
      }
      return resp
    },
    async sendAdminMessageData ({ commit, rootState }, playload) {
      // console.log(playload)
      let data = {}
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      const resp = await sendMessageRecord(data)
      return resp
    },
    async getAdminMessageCurrentRow ({ commit, rootState }, row) {
      commit(ADMIN_MESSAGE_CURRENT_ROW, row)
    },
    async changeAdminMessagePage ({ commit, rootState }, index) {
      let data = rootState.adminMessage.adminMessageList
      let _start = (index - 1) * rootState.adminMessage.adminMessagePageSize
      let _end = index * rootState.adminMessage.adminMessagePageSize
      commit(ADMIN_MESSAGE_HISTORY_DATA, data.slice(_start, _end))
    },
    async changeAdminMessagePageSize ({ commit, rootState }, value) {
      commit(ADMIN_MESSAGE_PAGE_SIZE, value)
    }
  }
}
